<template>
  <div class="roles-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAddRole" :disabled="!canRoleOperate()">
        <el-icon>
          <Plus />
        </el-icon>
        添加角色
      </el-button>
    </div>

    <!-- 角色列表 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="table-header">
          <span>角色列表</span>
          <div class="table-actions">
            <el-button size="small" @click="handleRefresh">
              <el-icon>
                <Refresh />
              </el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="roleList" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column prop="isActived" label="状态" width="150">
          <template #default="{ row }">
            <el-tag :type="(row.isActived ?? row.IsActived) ? 'success' : 'danger'">
              {{ (row.isActived ?? row.IsActived) ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataRange" label="数据范围" width="180" />
        <el-table-column prop="createdAt" label="创建时间" width="200" />
        <el-table-column prop="remarks" label="备注" width="150" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" :disabled="!canRoleOperate()">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button size="small" type="warning" @click="handlePermissions(row)" :disabled="!canRoleOperate()">
              <el-icon>
                <Setting />
              </el-icon>
              权限
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="!canRoleOperate()">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="状态" prop="isActived">
          <el-switch v-model="roleForm.isActived" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="数据范围" prop="dataRange">
          <el-select v-model="roleForm.dataRange" placeholder="请选择数据范围">
            <el-option label="全部数据" value="All" />
            <el-option label="部门数据" value="Department" />
            <el-option label="个人数据" value="Self" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="roleForm.remarks" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限分配" width="800px" @close="handlePermissionDialogClose">
      <div class="permission-tree">
        <el-tree ref="permissionTreeRef" :data="permissionTree" show-checkbox node-key="id"
          :default-checked-keys="checkedPermissions" :props="{
            children: 'children',
            label: 'name'
          }" @check="handlePermissionCheck" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions" :loading="permissionLoading">
            保存权限
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Edit,
  Delete,
  Switch,
  Setting
} from '@element-plus/icons-vue'
import roleAPI from '@/api/role'
import permissionAPI from '@/api/permission'
import { getPermissionChineseName } from '@/utils/permissionMapping'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const roleFormRef = ref(null)
const selectedRoles = ref([])

// 权限对话框
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const permissionTreeRef = ref(null)
const checkedPermissions = ref([])
const currentRole = computed(() => {
  const info = userStore.userInfo || {}
  if (Array.isArray(info.roles) && info.roles.length > 0) return info.roles[0]
  return info.role || 'User'
})
const canRoleOperate = () => currentRole.value === 'Boss' || currentRole.value === 'Manager'

// 角色表单
const roleForm = reactive({
  id: '',
  roleName: '',
  isActived: true,
  dataRange: 'All',
  remarks: ''
})

// 角色列表
const roleList = ref([])

// 权限树
const permissionTree = ref([])

// 表单验证规则
const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return roleForm.id ? '编辑角色' : '添加角色'
})

// 方法
const handleRefresh = () => {
  loadRoleList()
}

const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

const handleAddRole = () => {
  if (!canRoleOperate()) {
    ElMessage.error('权限不足')
    return
  }
  resetRoleForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  if (!canRoleOperate()) {
    ElMessage.error('权限不足')
    return
  }
  Object.assign(roleForm, {
    id: row.id,
    roleName: row.roleName,
    isActived: row.isActived ?? row.IsActived ?? true,
    dataRange: row.dataRange,
    remarks: row.remarks || row.Remarks || ''
  })
  dialogVisible.value = true
}

const handlePermissions = async (row) => {
  if (!canRoleOperate()) {
    ElMessage.error('权限不足')
    return
  }
  currentRole.value = row
  try {
    // 重置权限选择状态
    checkedPermissions.value = []

    // 先获取所有权限
    await loadPermissions()
    console.log('权限树数据:', permissionTree.value)

    // 获取角色权限
    const response = await roleAPI.getRolePermissions(row.id)
    console.log('角色权限响应:', response)

    if (response.code === 200 && Array.isArray(response.value)) {
      // 设置已选中的权限，兼容大小写字段名
      checkedPermissions.value = response.value.map(p => p.ID || p.id || p.PermissionId || p.permissionId)
      console.log('已选中的权限ID:', checkedPermissions.value)
    } else {
      checkedPermissions.value = []
    }

    // 确保权限树数据已加载
    if (permissionTree.value.length === 0) {
      ElMessage.warning('权限数据加载中，请稍后再试')
      return
    }

    permissionDialogVisible.value = true

    // 强制刷新权限树组件
    await nextTick()
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys(checkedPermissions.value)
    }
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 移除状态切换功能，因为后端没有这个功能

const handleDelete = async (row) => {
  if (!canRoleOperate()) {
    ElMessage.error('权限不足')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.roleName}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用API删除角色
    await roleAPI.deleteRole(row.id)
    ElMessage.success('删除成功')
    await userStore.refreshUserInfo()
    await loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

const handleSubmit = async () => {
  if (!roleFormRef.value) return

  try {
    await roleFormRef.value.validate()
    submitLoading.value = true

    // 调用API保存角色
    if (roleForm.id) {
      console.log(roleForm)
      // 更新角色
      await roleAPI.updateRole(roleForm.id, roleForm)
      ElMessage.success('更新成功')
      // 如果当前登录用户的角色被修改，刷新用户信息
      await userStore.refreshUserInfo()
    } else {
      // 添加角色
      await roleAPI.addRole(roleForm)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    await loadRoleList()
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存角色失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetRoleForm()
}

const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: '',
    roleName: '',
    isActived: true,
    dataRange: 'All',
    remarks: ''
  })
  roleFormRef.value?.clearValidate()
}

const handlePermissionCheck = (data, checkedInfo) => {
  console.log('权限选择变化:', data, checkedInfo)
}

const handlePermissionDialogClose = () => {
  // 重置权限选择状态
  checkedPermissions.value = []
  currentRole.value = null
  console.log('权限对话框已关闭，状态已重置')
}

const handleSavePermissions = async () => {
  if (!permissionTreeRef.value) return

  try {
    permissionLoading.value = true

    // 获取选中的权限
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

    console.log('选中的权限ID:', allCheckedKeys)

    // 先移除所有权限
    await roleAPI.removeRolePermissions(currentRole.value.id)

    // 重新分配权限
    for (const permissionId of allCheckedKeys) {
      await roleAPI.assignPermissions({
        roleId: currentRole.value.id,
        permissionId: permissionId
      })
    }

    ElMessage.success('权限保存成功')
    permissionDialogVisible.value = false
    // 重置权限选择状态
    checkedPermissions.value = []
    currentRole.value = null
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  } finally {
    permissionLoading.value = false
  }
}

const loadRoleList = async () => {
  loading.value = true
  try {
    const response = await roleAPI.getRoles()
    if (response.code !== 200 || !Array.isArray(response.value)) {
      ElMessage.error(response.msg || '获取角色列表失败')
      roleList.value = []
      return
    }
    // 兼容大驼峰和小驼峰
    roleList.value = response.value.map(item => ({
      id: item.id || item.ID,
      roleName: item.roleName || item.RoleName,
      dataRange: item.dataRange || item.DataRange,
      isActived: item.isActived ?? item.IsActived ?? true,
      createdAt: item.createdAt || item.CreatedAt ? new Date(item.createdAt || item.CreatedAt).toLocaleString() : '',
      remarks: item.remarks || item.Remarks
      // 可根据需要补充其它字段
    }))
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    roleList.value = []
  } finally {
    loading.value = false
  }
}

const loadPermissions = async () => {
  try {
    const response = await permissionAPI.getPermissions()
    console.log('权限API响应:', response)

    if (response.code !== 200 || !Array.isArray(response.value)) {
      ElMessage.error(response.msg || '获取权限列表失败')
      permissionTree.value = []
      return
    }

    // 清空之前的权限树数据
    permissionTree.value = []

    // 将权限列表转换为树形结构，兼容大小写字段名，并转换为中文名称
    permissionTree.value = response.value.map(permission => {
      const permissionName = permission.PermissionName || permission.permissionName || '未知权限'
      const chineseName = getPermissionChineseName(permissionName)
      console.log(`权限映射: ${permissionName} -> ${chineseName}`)
      return {
        id: permission.ID || permission.id,
        name: chineseName,
        originalName: permissionName, // 保留原始名称用于调试
        children: []
      }
    })
    console.log('权限树数据:', permissionTree.value)
    console.log('原始权限数据:', response.value)
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
    permissionTree.value = []
  }
}

// 生命周期
onMounted(() => {
  loadRoleList()
  loadPermissions()
})
</script>

<style lang="scss" scoped>
.roles-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
      font-weight: 600;
    }
  }

  .table-card {
    border-radius: 8px;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #303133;

      .table-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  .permission-tree {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
